#define _CRT_SECURE_NO_WARNINGS 1
#include "list.h"

LTNode* BuyListNode(LTDataType x)
{
	LTNode* newnode=(LTNode*)malloc(sizeof(LTNode));
	if (newnode==NULL)
	{
		perror("malloc fail");
	}

	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->data = x;

	return newnode;
}

LTNode* LTInit()
{
	LTNode* phead = BuyListNode(-1);

	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void LTPrint(LTNode* phead)
{
	assert(phead);

	printf("<=head=>");
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d<=>",cur->data);
		cur = cur->next;
	}

	printf("\n");
}

void LPDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(phead);

}
void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;

}

bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;

	tailprev->next = phead;
	phead->prev = tailprev;

	free(tail);
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = BuyListNode(x);
	LTNode* first = phead->next;

	newnode->next = first;
	first->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	LTNode* tail = phead->next;
	LTNode* tailnex = tail->next;

	phead->next = tailnex;
	tailnex->prev = phead;

	free(tail);
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		if (cur->data==x)
		{
			return cur;
		}
		cur = cur->next;
	}

	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode= BuyListNode(x);
	LTNode* posprev = pos->prev;

	newnode->next = pos;
	pos->prev = newnode;
	posprev->next = newnode;
	newnode->prev = posprev;
}

void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* posprev = pos->prev;
	LTNode* posnex = pos->next;

	posprev->next = posnex;
	posnex->prev = posprev;

	free(pos);
}